






//
//  BaseRequest.m
//  XJMCustomer
//
//  Created by Mr.hu on 2017/10/9.
//  Copyright © 2017年 Mr.hu. All rights reserved.
//

#import "BaseRequest.h"

@interface BaseRequest ()
{
    
    NSURLSessionDataTask *_request;
    XJAFNCliect *_client;
}

@end


@implementation BaseRequest

- (void)dealloc
{
    _agrs=nil;
    _host=nil;
    _requestMethod=nil;
    
}

- (id)init
{
    
    self = [super init];
    if (self) {
        _access = false;
        _client = [XJAFNCliect sharedClient];
    }
    
    return self;
    
}
-(NSMutableDictionary *)agrs{
    if (!_agrs) {
        _agrs=[NSMutableDictionary dictionary];
    }
    return _agrs;
}
//请求开始
- (void)start
{
    //组合请求URL
    NSString *requestURLString = [NSString stringWithFormat:@"%@%@", self.host, self.actionKey];
    //    [_client.requestSerializer setValue:[ToolClass getToken] forHTTPHeaderField:@"Authorization"];
    
    //交互式请求需要加入UserId
    if (_access) {
        NSString *accessToken = [XJToolClass getUserId];
        if ([XJToolClass getUserId]) {
            [self.agrs setObject:accessToken forKey:@"0-tid"];
        }
    }
    
    if ([self.requestMethod compare:@"GET" options:NSCaseInsensitiveSearch] == NSOrderedSame){
        
        _request = [_client getRequest:requestURLString parameters:_agrs completion:^(id result, NSError *error) {
            if (result) {
                [self resolveData:result];
            } else {
                NSLog(@"ERROR: %@", error);
                [self resolveError];
            }
        }];
        
    }else if ([self.requestMethod compare:@"PUT" options:NSCaseInsensitiveSearch] == NSOrderedSame){
        _request = [_client putRequest:requestURLString parameters:_agrs completion:^(id result, NSError *error) {
            if (result) {
                [self resolveData:result];
            } else {
                NSLog(@"ERROR: %@", error);
                [self resolveError];
            }
        }];
    }else if ([self.requestMethod compare:@"DELETE" options:NSCaseInsensitiveSearch] == NSOrderedSame){
        _request = [_client deleteRequest:requestURLString parameters:_agrs completion:^(id result, NSError *error) {
            if (result) {
                [self resolveData:result];
            } else {
                NSLog(@"ERROR: %@", error);
                [self resolveError];
            }
        }];
    }else{
        NSLog(@"params: %@",_agrs);
        _request = [_client postRequest:requestURLString parameters:_agrs completion:^(id result, NSError *error) {
            if (result) {
                [self resolveData:result];
            } else {
                NSLog(@"ERROR: %@", error);
                [self resolveError];
            }
        }];
    }
}

//上传data
-(void)updateData:(NSData *)data
{
    //组合请求URL
    NSString *requestURLString = [NSString stringWithFormat:@"%@%@", self.host, self.actionKey];
    //交互式请求需要加入UserId
    if (_access) {
        NSString *accessToken = [XJToolClass getUserId];
        [_agrs setObject:accessToken forKey:@"0-tid"];
    }
    _request = [_client dataRequest:requestURLString parameters:_agrs data:data completion:^(id result, NSError *error) {
        if (result) {
            [self resolveData:result];
        } else {
            NSLog(@"ERROR: %@", error);
            [self resolveError];
        }
    }];
}

//上传data
-(void)updateData:(NSData *)data Name:(NSString *)name{
    //组合请求URL
    NSString *requestURLString = [NSString stringWithFormat:@"%@%@", self.host, self.actionKey];
    
    //交互式请求需要加入UserId
    if (_access) {
        NSString *accessToken = [XJToolClass getUserId];
        [_agrs setObject:accessToken forKey:@"0-tid"];
    }
    _request = [_client dataRequest:requestURLString parameters:_agrs data:data  dataName:name completion:^(id result, NSError *error) {
        if (result) {
            [self resolveData:result];
        } else {
            NSLog(@"ERROR: %@", error);
            [self resolveError];
        }
    }];
}

-(void)updateImages:(NSArray *)images names:(NSArray *)names{
    
    //组合请求URL
    NSString *requestURLString = [NSString stringWithFormat:@"%@%@", self.host, self.actionKey];
    //交互式请求需要加入UserId
    if (_access) {
        NSString *accessToken = [XJToolClass getUserId];
        [_agrs setObject:accessToken forKey:@"0-tid"];
    }
    
    _request = [_client dataRequest:requestURLString parameters:_agrs datas:images dataNames:names completion:^(id result, NSError *error)
                {
                    if (result) {
                        [self resolveData:result];
                    } else {
                        NSLog(@"ERROR: %@", error);
                        [self resolveError];
                    }
                }];
}

// 将JSON串转化为字典或者数组
- (id)toArrayOrNSDictionary:(NSData *)jsonData{
    
    NSError *error = nil;
    id jsonObject = [NSJSONSerialization JSONObjectWithData:jsonData
                                                    options:NSJSONReadingAllowFragments
                                                      error:&error];
    
    //数据解析
    NSString * friendstg =[[NSString alloc]initWithData:jsonData encoding:NSUTF8StringEncoding];
    NSLog(@"friendstg:%@",friendstg);
    
    
    if (jsonObject != nil && error == nil){
        return jsonObject;
    }else{
        // 解析错误
        return nil;
    }
    
}

//解析返回数据
-(void)resolveData:(id)data
{
    NSMutableDictionary *dic = [self toArrayOrNSDictionary:data];
    NSLog(@"nsmutable:%@",dic);
    
    //解密JSon
    //    NSLog(@"test=================%s===================",[[dic description]UTF8String]);
    
    if (dic==nil)
    {
        NSLog(@"there is no datas");
        return;
    }
    
    NSInteger status = [[dic objectForKey:@"code"]integerValue];
    //成功返回
    if (status == 0) {
        if (self.delegate && [self.delegate respondsToSelector:@selector(request:successLoadData:)]) {
            [self.delegate request:self successLoadData:[dic objectForKey:@"data"]];
        }
    }
    
    //返回错误信息码
    else if (status == 1) {
        NSString *errorMsg =[dic objectForKey:@"message"];
        NSLog(@"错误信息=%@",errorMsg);
        if (self.delegate && [self.delegate respondsToSelector:@selector(request:failLoadDataWithErrorCode:)]) {
            [self.delegate request:self failLoadDataWithErrorCode:errorMsg];
        }
        
    }else{
        if (self.delegate && [self.delegate respondsToSelector:@selector(request:failedWithError:)]) {
            NSString *errorMsg =[dic objectForKey:@"message"];
            NSLog(@"错误信息=%@",errorMsg);
            [self.delegate request:self failedWithError:errorMsg];
        }
    }
}

//处理错误
-(void)resolveError
{
    if (self.delegate && [self.delegate respondsToSelector:@selector(request:failLoadDataWithErrorCode:)]) {
        [self.delegate request:self failLoadDataWithErrorCode:nil];
    }
}

//取消请求
- (void)cancel
{
    [_request cancel];
    _request = nil;
}

@end
